package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.example.exception.CustomException;
import com.example.mapper.AppointmentMapper;
import com.example.mapper.OrderMapper;
import com.example.mapper.OwnerMapper;
import com.example.mapper.RoomMapper;
import com.example.pojo.Account;
import com.example.pojo.Admin;
import com.example.pojo.LoginResponse;
import com.example.pojo.Owner;
import com.example.service.OwnerService;
import com.example.util.JwtUtil;
import com.example.util.Md5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OwnerServiceImpl implements OwnerService {
    @Resource
    private OwnerMapper ownerMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private AppointmentMapper appointmentMapper;

    /**
     * 添加用户
     *
     * @param owner
     */
    @Override
    public void add(Owner owner) {
        Owner dbOwner = ownerMapper.selectByUsername(owner.getUsername());
        if (dbOwner!=null){
            throw new CustomException("500","账号已存在");
        }
        if (StrUtil.isBlank(owner.getPassword())){//未填密码
            owner.setPassword("12345");//设置默认密码
        }

        if (StrUtil.isBlank(owner.getName())){//未填姓名
            owner.setName(owner.getUsername());//设置账号为默认姓名
        }

        if (StrUtil.isBlank(owner.getAvatar())){
            owner.setAvatar("https://house1205.oss-cn-shenzhen.aliyuncs.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png");
        }
        owner.setRole("owner");//设置角色为普通房东

        String md5String = Md5Util.getMD5String(owner.getPassword());//加密密码
        owner.setPassword(md5String);

        ownerMapper.add(owner);
    }

    /**
     * 注册
     *
     * @param owner
     */
    @Override
    public void register(Owner owner) {
        this.add(owner);
    }

    /**
     * 修改密码
     *
     * @param account
     */
    @Override
    public void updatePassword(Account account,@RequestHeader("Authorization") String token) {
        Integer id = account.getId();
        Owner dbOwner = ownerMapper.selectById(id);
        if (!dbOwner.getPassword().equals(Md5Util.getMD5String(account.getPassword()))){
            throw new CustomException("500","原密码错误");
        }
        dbOwner.setPassword(Md5Util.getMD5String(account.getNewPassword()));

        this.updateById(dbOwner);

        //修改密码后，注销token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
    }

    /**
     * 登录
     *
     * @param account
     */
    @Override
    public LoginResponse login(Account account) {
        String username = account.getUsername();//账号
        Owner dbOwner = ownerMapper.selectByUsername(username);
        if (dbOwner == null){
            throw new CustomException("500","账号不存在");
        }
        String password = account.getPassword();//密码
        if (!Md5Util.checkPassword(password,dbOwner.getPassword())){
            throw new CustomException("500","用户名或密码错误");
        }

        //登录成功
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",dbOwner.getId());
        claims.put("username",username);
        claims.put("name",dbOwner.getName());
        claims.put("role",dbOwner.getRole());
        //登录成功后，返回token
        String token = JwtUtil.genToken(claims);

        //把token存储到redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,2, TimeUnit.HOURS);//过期时间 2小时

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setAccount(dbOwner);
        loginResponse.setToken(token);

        return loginResponse;
    }

    /**
     * 根据账号查询用户
     *
     * @param username
     */
    @Override
    public Owner selectByUsername(String username) {
        Owner owner = ownerMapper.selectByUsername(username);
        return owner;
    }

    @Override
    public Map<String, Object> statistcs(Integer ownerId) {
        Map<String, Object> statistics = new HashMap<>();
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);

        // 获取今日订单数和收入
        int todayOrders = orderMapper.countTodayOrders(ownerId, today);
        double todayIncome = orderMapper.sumTodayIncome(ownerId, today);

        // 获取昨日订单数和收入用于计算环比
        int yesterdayOrders = orderMapper.countTodayOrders(ownerId, yesterday);
        double yesterdayIncome = orderMapper.sumTodayIncome(ownerId, yesterday);

        // 计算环比变化
        double orderChange = yesterdayOrders == 0 ? 0 : ((todayOrders - yesterdayOrders) * 100.0 / yesterdayOrders);
        double incomeChange = yesterdayIncome == 0 ? 0 : ((todayIncome - yesterdayIncome) * 100.0 / yesterdayIncome);

        // 获取房间统计
        Map<String, Integer> roomStats = roomMapper.getRoomStatistics(ownerId);

        // 获取待处理预约
        int pendingAppointments = appointmentMapper.countPendingAppointments(ownerId);
        int todayNewAppointments = appointmentMapper.countTodayNewAppointments(ownerId, today);

        // 组装统计数据
        statistics.put("todayOrders", todayOrders);
        statistics.put("orderChange", Math.round(orderChange * 10) / 10.0); // 保留一位小数
        statistics.put("todayIncome", Math.round(todayIncome * 100) / 100.0); // 保留两位小数
        statistics.put("incomeChange", Math.round(incomeChange * 10) / 10.0);
        statistics.put("totalRooms", roomStats.getOrDefault("total", 0));
        statistics.put("occupiedRooms", roomStats.getOrDefault("occupied", 0));
        statistics.put("availableRooms", roomStats.getOrDefault("available", 0));
        statistics.put("pendingAppointments", pendingAppointments);
        statistics.put("todayNewAppointments", todayNewAppointments);

        return statistics;
    }



    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<Owner> selectAll(Owner owner) {
        List<Owner> list = ownerMapper.selectAll(owner);
        return list;
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public Owner selectById(Integer id) {
        Owner owner = ownerMapper.selectById(id);
        return owner;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        ownerMapper.deleteById(id);
    }

    /**
     * 批量删除数据
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id:ids)
            ownerMapper.deleteById(id);
    }



    /**
     * 修改用户
     *
     * @param owner
     */
    @Override
    public void updateById(Owner owner) {
        ownerMapper.updateById(owner);
    }



    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Owner> selectPage(Owner owner, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Owner> list = ownerMapper.selectAll(owner);
        return PageInfo.of(list);
    }
}
